package com.ruoyi.system.common;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.utils.TencentCOSUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传
 */
@RestController
@RequestMapping("app/api/common")
@Api(tags = "上传文件相关接口")
@Slf4j
public class CommonFileController {

    @Autowired
    private TencentCOSUtil tencentCOSUtil;
    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @ApiOperation("app端上传图片")
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file)  {
        if(file.isEmpty()){
            throw new ServiceException("上传文件为空");
        }
        log.info("文件接口调用:{}",file);
//        //1.先获取原始文件名称
//        String originalFilename = file.getOriginalFilename();
//        //2.截取文件名的后缀
//        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //3.生成新的文件名
//        String newFileName = UUID.randomUUID().toString() + substring;
//        //4.定义文件夹
//        String destinationFilePath = "E:/images/";
//
//        File directory = new File(destinationFilePath);
//
//        // 创建目录
//        if (!directory.exists()) {
//            directory.mkdirs();
//            System.out.println("目录创建成功: " + directory);
//        }
//        file.transferTo(new File(directory,newFileName));
        String fileUrl = null;
        try {
            fileUrl = tencentCOSUtil.upLoadFile(file);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传文件失败");
        }
        AjaxResult ajax=new AjaxResult();
        ajax.put("fileUrl：",fileUrl);
        ajax.put("videoName：",file.getOriginalFilename());
        return AjaxResult.success("上传成功！", ajax);

    }
}
